<!--
 * @Author: weidewei
 * @Date: 2025-11-12 09:22:18
 * @LastEditors: weidewei
 * @LastEditTime: 2025-11-12 10:11:39
 * @Description: 
 * @FilePath: \2025-front-face\review-knowledge\20251112\复习数组去重.html
-->
<script>
    const arr = [1,2,3,4,5,6,2,3,4];
    const arrObj = [
        {
          name: "张三",
          age: 18  
        },
        {
          name: "李四",
          age: 21  
        },
        {
          name: "王五",
          age: 20  
        },
        {
          name: "王五",
          age: 22 
        },
    ]
    // new Set
    // function uniqueArr(arr) {
    //     return [...new Set(arr)]
    // }
    // console.log(uniqueArr(arr));

    // for循环+indexOf
    // function uniqueArr1(arr) {
    //     const result = [];
    //     for(let i=0;i<arr.length;i++) {
    //         if(result.indexOf(arr[i]) === -1) {
    //             result.push(arr[i]);
    //         }
    //     }
    //     return result;
    // }
    // console.log(uniqueArr1(arr));

    // filter+indexOf
    //  function uniqueArr2(arr) {
    //     return arr.filter((item,index)=>{
    //         // 如果两者相等，说明是第一次出现，保留；否则是重复元素，过滤掉
    //         return arr.indexOf(item) === index;
    //     })
    //  }
    //  console.log(uniqueArr2(arr));

     // reduce+indexOf
     function uniqueArr3(arr) {
        return arr.reduce((prev,cure)=>{
            if(prev.indexOf(cure) === -1) {
                prev.push(cure);
            }
            return prev
        },[])
     }
    //  console.log(uniqueArr3(arr));

     // 数组对象去重
     function uniqueArr4(arr,key) {
        const result = {};
        return arr.reduce((prev,cure)=>{
            const objKeyVal = cure[key];
            if(!result[objKeyVal]) {
                console.log(cure);
                result[objKeyVal] = cure;
                prev.push(cure);
            }
            console.log('result',result)
            return prev;
        },[])
     }
     console.log(uniqueArr4(arrObj,'name'));
</script>